package com.glodon.fansi.webui.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.glodon.fansi.common.AjaxResult;
import com.glodon.fansi.db.model.User;
import com.glodon.fansi.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	@RequestMapping("/dologin")
	@ResponseBody
	public AjaxResult login(@RequestParam("account") String account, @RequestParam("password") String password, ModelMap model, HttpSession session) {
		User user = userService.login(account, password);
		if (user == null) {
			return AjaxResult.newError("用户名或密码错误");
		}
		model.put("user", user);
		session.setAttribute("user", user);
		return AjaxResult.newSuccsess("登录成功，正在跳转...");
	}

	@RequestMapping("/logout")
	public String logout(  HttpSession session) {
		session.removeAttribute("user");
		session.invalidate();
		return "/login";
	}

	@RequestMapping("/{account}/admin/profile")
	public String beforeedit(@PathVariable("account") String account, ModelMap model) {
		User editUser = userService.selectByAccount(account);
		model.put("editUser", editUser);
		return "/user/userinfo";
	}

	@RequestMapping("/admin/profile/update_basic_info")
	@ResponseBody
	public AjaxResult edit(User user) {
		logger.debug("{}", user);
		int i = userService.updateByPrimaryKeySelective(user);
		if (i > 0) {
			return AjaxResult.newSuccsess("用户资料修改成功");
		} else {
			return AjaxResult.newError("用户信息修改失败");
		}

	}

	@RequestMapping("/loginjson")
	@ResponseBody
	public User loginjson(@RequestParam("account") String account, @RequestParam("password") String password) {
		User user = userService.login(account, password);
		return user;
	}
}
